package just.stuff.morsels.ui.user;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map.Entry;

import just.stuff.morsels.MorselSession;

import org.apache.wicket.RequestCycle;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.protocol.http.RequestUtils;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;

public final class LoginLink extends Link<Void> {
	private final String pageUrl;

	public LoginLink(String id, String pageUrl) {
		super(id);
		this.pageUrl = pageUrl;
	}

	@Override
	public void onClick() {
		String loginURL = LoginLink.createLoginURL();
		MorselSession.get().setLoginRedirectUrl( pageUrl );
		getRequestCycle().setRequestTarget( new RedirectRequestTarget( loginURL ) );
	}

	@Override
	public boolean isVisible() {
		return !MorselSession.isSignedIn();
	}

	private static String createLoginURL() {
			final HashMap<String, String> query = new HashMap<String, String>();
			query.put( "openid.ns", "http://specs.openid.net/auth/2.0" );
			query.put( "openid.ns.pape", "http://specs.openid.net/extensions/pape/1.0" );
			query.put( "openid.claimed_id", "http://specs.openid.net/auth/2.0/identifier_select" );
			query.put( "openid.identity", "http://specs.openid.net/auth/2.0/identifier_select" );
			String callbackPath = RequestUtils.toAbsolutePath( RequestCycle.get().getRequest().getRelativePathPrefixToContextRoot() )+"login";
			query.put( "openid.return_to", callbackPath );
	//		query.put( "openid.realm", "http://www.example.com/" );
			query.put( "openid.mode", "checkid_setup" );
			query.put( "openid.ns.ax", "http://openid.net/srv/ax/1.0" );
			query.put( "openid.ax.mode", "fetch_request" );
			query.put( "openid.ax.type.email", "http://axschema.org/contact/email" );
			query.put( "openid.ax.type.language", "http://axschema.org/pref/language" );
			query.put( "openid.ax.required", "email,language" );
			
			StringBuilder sb = new StringBuilder( "https://www.google.com/accounts/o8/ud?" );
			boolean first = true;
			for( Entry<String, String> entry : query.entrySet() ) {
				if( !first ) {
					sb.append( '&' );
				}
				sb.append( entry.getKey() );
				sb.append( '=' );
				try {
					sb.append( URLEncoder.encode( entry.getValue(), "iso-8859-1" ) );
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException( e );
				}
				first = false;
			}
			String loginURL = sb.toString();
			return loginURL;
		}
}